var mongoose = require('mongoose')
var Schema = mongoose.Schema

const shelfSchema = Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  },
  book: {
    type: Schema.Types.ObjectId,
    ref: 'Book'
  },
  created_at: Date,
  updated_at: Date
})

shelfSchema.pre('save', function (next) {
  const shelf = this
  if (!shelf.isModified || !shelf.isNew) {
    next()
  } else {
    const currentDate = new Date()
    shelf.updated_at = currentDate
    if (!shelf.created_at)
      shelf.created_at = currentDate
    next()
  }
})

module.exports = mongoose.model('Shelf', shelfSchema)
